package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.util.Json;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper1 setmealMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public Result add(DishDTO dishDTO) {
        //进行非空判断
        if (dishDTO.getCategoryId() == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //2.新增菜品表，一条数据，当事务没有提交之前，我们必须返回菜品id，供新增口味使用调用mappre
        //进行映射
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.add(dish);
        //3.新增口味集合，多条数据，执行批量新增，一定要拿到菜品id
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
            dishFlavorMapper.insertBatch(flavors);
        }
        //清理缓存数据
        String key="dish_"+dishDTO.getCategoryId();
        cleanCache(key);
        //返回值
        return Result.success();
    }

    /**
     * 查询分页
     *
     * @param dto
     */
    @Override
    public Result page(DishPageQueryDTO dto) {
        //进行页数加载数据的非空判断
        if (dto.getPage() == null) {
            dto.setPage(1);
        }
        if (dto.getPageSize() == null) {
            dto.setPageSize(10);
        }
        //2.执行分页
        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        //3.条件查询
        Page<Dish> page = dishMapper.pagefind(dto);
        //3.1 总条数以及菜品集合
        long total = page.getTotal();
        List<Dish> dishList = page.getResult();

        //3.3声明一个list用来承载vo对象集合
        List<DishVO> dishVoList = new ArrayList(dishList.size());

        //3.2 为每一条数据添加菜品分类名称
        dishList.forEach(dish -> {
            //1.声明一个vo对象
            DishVO vo = new DishVO();
            BeanUtils.copyProperties(dish, vo);
            //2.获取分类名称
            Category category = categoryMapper.getById(vo.getCategoryId());
            vo.setCategoryName(category.getName());
            //3.写入数据到voList
            dishVoList.add(vo);
        });
        //4.返回数据
        PageResult pageResult = new PageResult();
        pageResult.setRecords(dishVoList);
        pageResult.setTotal(total);
        return Result.success(pageResult);
    }

    /**
     * 删除数据
     *
     * @param ids
     */
    @Override
    @Transactional
    public Result delete(List<Long> ids) {
        //1.非空判断
        if (ids == null || ids.size() == 0) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //2.查询当前菜品是否存在
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            //3.如果存在，判断状态如果是起售状态，则不能删除
            if (dish != null) {
                if (dish.getStatus() == StatusConstant.ENABLE) {
                    return Result.error(MessageConstant.DISH_ON_SALE);
                }
            }
        }

        //4.如果存在，被套餐关联的话也不能删除
        List<Long> setmealDishIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealDishIds != null && setmealDishIds.size() > 0) {
            return Result.error(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //5.如果存在，删除菜品之后，口味数据也删除
        dishMapper.deleteDish(ids);
        dishFlavorMapper.deleteDishFlavor(ids);

        //将所有的菜品缓存数据清理掉，所有以dish_开头的key
        cleanCache("dish_*");
        //6.返回数据
        return Result.success();
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     */
    @Override
    public Result getById(Long id) {
        //1.非空判断
        if (id == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //2.根据id查询当前数据
        //2.1 查询菜品
        Dish dish = dishMapper.getById(id);
        //2.2查询口味
        List<DishFlavor> dishFlavorList = dishFlavorMapper.getDishFalvorListById(id);

        //2.3 口味关联到菜品中
        DishVO vo = new DishVO();
        BeanUtils.copyProperties(dish, vo);
        vo.setFlavors(dishFlavorList);

        //3.如果存在，则返回数据
        return Result.success(vo);

    }

    /**
     * 套餐需求根据分类id查询菜品
     *
     * @param categoryId
     */
    @Override
    public Result list(Long categoryId) {
        Dish dish=Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        List<Dish> list = dishMapper.getId(dish);
        return Result.success(list);
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     */
    @Override
    public Result update(DishDTO dishDTO) {
        //1.非空判断
        if (dishDTO.getId() == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //2.根据id修改dish表
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.updateDishById(dish);

        //3.根据菜品id去删除口味表数据集合
        dishFlavorMapper.deleteDishFlavor(Arrays.asList(dishDTO.getId()));


        //4.插入新的口味数据到口味表中
        List<DishFlavor> flavors = dishDTO.getFlavors();//每个DishFlavor只包含了name和value,并不包含dish_id
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
            dishFlavorMapper.insertBatch(flavors);
        }
        //将所有的菜品缓存数据清理掉，所有以dish_开头的key
        cleanCache("dish_*");
        return Result.success();
    }

    /**
     * 修改启用类
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public Result updatestatus(Integer status, Long id) {
        //非空判断
        if (id == null) {
            return Result.error(MessageConstant.ACCOUNT_NOT_CM);
        }
        if (status == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //调用mapper
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.updateDishById(dish);
        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
        //将所有的菜品缓存数据清理掉，所有以dish_开头的key
        cleanCache("dish_*");
        //返回
        return Result.success();
    }

    /**
     * 用户端
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        //设置key的名字
        String key="dish_"+dish.getCategoryId();
        //查询Redis是否存在数据，有就返回
        String dishvodis = redisTemplate.opsForValue().get(key);
        //把String转换成list集合
        List<DishVO> dishVOList1 = JSONArray.parseArray(dishvodis, DishVO.class);
        if(dishVOList1 !=null && dishVOList1.size()>0){
        return dishVOList1;
        }
        //如果没有就查询数据库，在写入Redis中
        List<Dish> dishList = dishMapper.getId(dish);
        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);
            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getDishFalvorListById(d.getId());
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        //写入到Redis中
        redisTemplate.opsForValue().set(key, JSON.toJSONString(dishVOList));
        return dishVOList;
    }

    /**
     * 清理缓存方法
     * @param pattern
     */
    private void cleanCache(String pattern){
        //获取Redis使用的key
        Set<String> keys = redisTemplate.keys(pattern);
        //进行清除
        redisTemplate.delete(keys);
    }
}
